< previous page page_462 next page >

Page 462
The problem here is that after you press the Tab key, the next field in the tab order receives focus. This means that next text box has fired its GotFocus() event and that control now has the input focus. After this occurs, the LostFocus() event for the previous text box fires. In the code for the LostFocus() on the original text box, you invoke the SetFocus method to set focus back to the original text box. In the text box that now has focus, however, you have the same type of code in its LostFocus() event. This means it will lose focus as soon as you perform the SetFocus event on the original text box. However, focus has then gone to the original text box, which means that the LostFocus() event will now fire on the other control, which then sets focus back to itself. Well, as you can see, you are now in an infinite loop. This is known as a deadly embrace, a computer science term used when two objects are fighting for a single resource (in this case, the input focus).
To break out of the deadly embrace when using the Visual Basic design environment, press Ctrl+Break to enter break mode. If you have this code in a compiled EXE file, youll need to bring up Task Manager to end the task.
The Validate Event
To avoid the problem with the LostFocus() event, Microsoft has added a new event called Validate that allows you to check the value in a text box or other control prior to it losing the focus. The Validate event can be used to perform any type of validation you require. You can use it to check for blank data, to see whether a minimum number of characters have been input, to make sure only numbers are input, and even to verify that a valid date has been entered.
The Validate event is passed in a Cancel argument that you can set to a True value if you want to cancel the LostFocus event. If you set this argument to False, the LostFocus will occur normally. Within the Validate event, you write any type of code needed to ensure you have valid data. For example, the following code checks to see whether a first name field is filled in with any data and that the user has input at least three characters:
9f31265bb40b592b1929e18a47ab28e5.gif
Private Sub txtFirstValidate_Validate(Cancel As Boolean)
   If Trim$(txtFirstValidate.Text) = "" Then
      MsgBox "First Name Field Must Be Filled In"
      Cancel = True
   ElseIf Len(Trim$(txtFirstValidate.Text)) < 3 Then
      MsgBox "You must enter more than 2 letters"
      Cancel = True

 
< previous page page_462 next page >

If you like this book, buy it!